/*
 * File:   TUFile.cpp
 * Author: ARSchmitz
 *
 * Created on April 24, 2011
 */
#include <cstdio>
#include <cstring>
#include <iostream>
#include "TigerUpdate.h"

void *TUFile::operator new(unsigned long size){
    printf("DEBUG: TUFile.new(1) - %ld %ld\n", size, sizeof(TUFile));
    void *result = malloc(size);
    return result;
}

TUFile::TUFile() : TUObject(NULL){
    printf("DEBUG: TUFile.TUFile(0)\n");
    //TUFile(NULL, (FILE *)NULL);
}

void *TUFile::operator new(unsigned long in_size, const char *filename, FILE *file){
    long size = TUFile::getFileSize(file);
    printf("DEBUG: TUFile.new(3) - %ld %ld %ld\n", size, in_size, sizeof(TUFile));
    // Needed because myData is a variable length array.
    return malloc(in_size + size);
}

TUFile::TUFile(const char *filename, FILE *file) : TUObject(NULL){
    printf("DEBUG: TUFile.TUFile(2)\n");
    long size = getFileSize(file);
    // Needed because myData is a variable length array.
    //TUFile *me = (TUFile *) realloc(this, sizeof(TUFile) + size);
    //this = me;

    currentFilePtr = 0;
    readBuffer[BUFSIZE] = '\0';
    
    myObjectType = TUFILE;
    strncpy(myName, filename, MAXNAME);
    myFileSize = size;
    //myData is located where it needs to be, nothings needs to be assigned

    // Copy file's data into the newly created space.
    if(fread(myData, 1, myFileSize, file) != myFileSize){
        this == NULL;
    }
}

TUFile::~TUFile(){
    delete this;
}

bool TUFile::operator ==(TUObject* object){
    return(
        (TUObject *)this == object &&
        this->myName == ((TUFile *)object)->myName);
}



char* TUFile::getFileName(){
    return myName;
}

void *TUFile::getFileData(){
    return myData;
}

bool TUFile::hasNext(){
    return false; //feof(myFile) == 0;
}

char* TUFile::getNext(){
    //int bytes = fread(readBuffer, 1, BUFSIZE-1, myFile);
    //if(bytes < BUFSIZE-1)
    //    readBuffer[bytes] = '\0';
    return readBuffer;
}

long TUFile::getFileSize(FILE *myFile){
    fpos_t currentPosition;
    long result = 0;

    fgetpos(myFile, &currentPosition);

    rewind(myFile);
    int bytes = 1;
    while(bytes = fread(NULL, 1, 1024, myFile) > 0)
      result += bytes;

    fsetpos(myFile, &currentPosition);
    return result;
}